package com.smzd.ccms.core;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;

/**
 * 给所有的ViewMapper做高速缓冲
 * 
 * @author YuZhongda
 * 
 */
public class ViewMapperCache {
	private static ViewMapperCache instance;

	public static ViewMapperCache getInstance() {
		if (instance == null) {
			synchronized (ViewMapperCache.class) {
				if (instance == null) {
					instance = new ViewMapperCache();
				}
			}
		}
		return instance;
	}

	private Map<String, ViewMapper> fixedCache = new HashMap<String, ViewMapper>();
	private Map<String, ViewMapper> varCache = new HashMap<String, ViewMapper>();

	/**
	 * 从固定模式中获取一个ViewMapper。如果没有匹配项，返回空值。
	 * 
	 * @param uri
	 * @return
	 */
	public static ViewMapper getViewMapper(String uri) {
		return instance.fixedCache.get(uri);
	}

	/**
	 * 从变量模式中获取一个ViewResult，内含ViewMapper和因匹配而得到的路径变量值。如果没有匹配项，返回空值。
	 * 
	 * @param uri
	 * @return
	 */
	public static ViewMapResult getViewMapperResult(String uri) {
		Set<ViewMapResult> set = new TreeSet<ViewMapResult>();
		for (ViewMapper vvm : instance.varCache.values()) {
			ViewMapResult mr = vvm.match(uri);
			System.out.println(mr);
			if (mr.isMatch()) {
				set.add(mr);
			}
		}
		if(set.size()>0){
			return set.iterator().next();
		}
		return null;
	}

	/**
	 * 添加一个映射
	 * 
	 * @param viewMapper
	 */
	public ViewMapperCache addViewMapper(ViewMapper viewMapper) {
		if(viewMapper.getVariableCount()==0){
			fixedCache.put(viewMapper.getUri(), viewMapper);
			System.out.println("添加一个静态ViewMapper！uri="+viewMapper.getUri());
		}else{
			varCache.put(viewMapper.getUri(), viewMapper);
			System.out.println("添加一个动态ViewMapper！uri="+viewMapper.getUri());
		}
		return this;
	}
}
